//
//  NSDate+ZSExtend.m
//  Epayment
//
//  Created by safiri on 2018/6/13.
//  Copyright © 2018年 safiri. All rights reserved.
//

#import "NSDate+ZSExtend.h"
#import "NSDate+YYAdd.h"

@implementation NSDate (ZSExtend)

+ (NSString *)timeWithTimeIntervalString:(NSString *)timeString andFormat:(NSString *)dateFormat {
    // 格式化时间
    NSDateFormatter *formatter = [NSDate formatter];
    //formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    //[formatter setDateStyle:NSDateFormatterMediumStyle];
    //[formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:dateFormat];
    
    // 单位为秒
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString *dateString = [formatter stringFromDate:date];
    return dateString;
}
+ (NSString *)timestampNow {
    // 当前时间
    NSDate *date = [NSDate date];
    NSTimeInterval a=[date timeIntervalSince1970]*1000; // *1000 是精确到毫秒，不乘就是精确到秒
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a]; //转为字符型
    return timeString;
}


+ (NSDate *)yesterday{
    return  [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)];
}

+ (NSDateFormatter *)formatter {
    static NSDateFormatter *formatter = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        formatter = [[NSDateFormatter alloc] init];
        //[formatter setDoesRelativeDateFormatting:YES];
    });
    
    return formatter;
}
+(NSDateFormatter *)formatterShort {
    
    static NSDateFormatter *formatter = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDoesRelativeDateFormatting:YES];
    });
    
    return formatter;
}

+(NSDateFormatter *)formatterWithoutTime {
    
    static NSDateFormatter *formatterWithoutTime = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        formatterWithoutTime = [[NSDate formatter] copy];
        [formatterWithoutTime setTimeStyle:NSDateFormatterNoStyle];
    });
    
    return formatterWithoutTime;
}

+(NSDateFormatter *)formatterWithoutDate {
    
    static NSDateFormatter *formatterWithoutDate = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        formatterWithoutDate = [[NSDate formatter] copy];
        [formatterWithoutDate setDateStyle:NSDateFormatterNoStyle];
    });
    
    return formatterWithoutDate;
}

#pragma mark -
#pragma mark Formatter with date & time
-(NSString *)formatWithUTCTimeZone {
    return [self formatWithTimeZoneOffset:0];
}

-(NSString *)formatWithLocalTimeZone {
    return [self formatWithTimeZone:[NSTimeZone localTimeZone]];
}

-(NSString *)formatWithTimeZoneOffset:(NSTimeInterval)offset {
    return [self formatWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:offset]];
    //GMT 0:00 格林威治标准时间
}

-(NSString *)formatWithTimeZone:(NSTimeZone *)timezone {
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setTimeZone:timezone];
    return [formatter stringFromDate:self];
}

#pragma mark -
#pragma mark Formatter without time
-(NSString *)formatWithUTCTimeZoneWithoutTime {
    return [self formatWithTimeZoneOffsetWithoutTime:0];
}

-(NSString *)formatWithLocalTimeZoneWithoutTime {
    return [self formatWithTimeZoneWithoutTime:[NSTimeZone localTimeZone]];
}

-(NSString *)formatWithTimeZoneOffsetWithoutTime:(NSTimeInterval)offset {
    return [self formatWithTimeZoneWithoutTime:[NSTimeZone timeZoneForSecondsFromGMT:offset]];
}

-(NSString *)formatWithTimeZoneWithoutTime:(NSTimeZone *)timezone {
    NSDateFormatter *formatter = [NSDate formatterWithoutTime];
    [formatter setTimeZone:timezone];
    return [formatter stringFromDate:self];
}

#pragma mark -
#pragma mark Formatter without date
-(NSString *)formatWithUTCWithoutDate {
    return [self formatTimeWithTimeZone:0];
}
-(NSString *)formatWithLocalTimeWithoutDate {
    return [self formatTimeWithTimeZone:[NSTimeZone localTimeZone]];
}

-(NSString *)formatWithTimeZoneOffsetWithoutDate:(NSTimeInterval)offset {
    return [self formatTimeWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:offset]];
}

-(NSString *)formatTimeWithTimeZone:(NSTimeZone *)timezone {
    NSDateFormatter *formatter = [NSDate formatterWithoutDate];
    [formatter setTimeZone:timezone];
    return [formatter stringFromDate:self];
}
#pragma mark -
#pragma mark Formatter  date
+ (NSString *)currentDateStringNorm
{
    return [self currentDateStringWithFormat:@"yyyy-MM-dd HH:mm:ss"];
}
+ (NSString *)currentDateStringNorm2
{
    return [self currentDateStringWithFormat:@"yyyyMMddHHmmss"];
}
+ (NSString *)currentDateStringNorm3
{
    return [self currentDateStringWithFormat:@"yyyy-MM-dd"];
}
+ (NSString *)currentDateStringWithFormat:(NSString *)format
{
    NSDate *chosenDate = [NSDate date];
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:format];
    NSString *date = [formatter stringFromDate:chosenDate];
    return date;
}
+ (NSDate *)dateWithSecondsFromNow:(NSInteger)seconds {
    NSDate *date = [NSDate date];
    NSDateComponents *components = [NSDateComponents new];
    [components setSecond:seconds];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *dateSecondsAgo = [calendar dateByAddingComponents:components toDate:date options:0];
    return dateSecondsAgo;
}

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSUInteger)month day:(NSUInteger)day {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}
- (NSString *)dateWithFormat:(NSString *)format
{
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:format];
    NSString *date = [formatter stringFromDate:self];
    return date;
}
- (NSString *)YMWithDate{
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:@"yyyy-MM"];
    return [formatter stringFromDate:self];
}

- (NSString *)MDWithDate{
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:@"MM-dd"];
    return [formatter stringFromDate:self];
}

- (NSString *)MDChineseWithDate{
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:@"MM月dd日"];
    return [formatter stringFromDate:self];
}

- (NSString *)HmsWithDate{
    NSDateFormatter *formatter = [NSDate formatter];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
    [formatter setDateFormat:@"HH:mm:ss"];
    return [formatter stringFromDate:self];
}

- (NSString *)YMDWithDate{
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [formatter stringFromDate:self];
}

- (NSString *)morningOrAfterWithHH{
    NSDateFormatter *formatter = [NSDate formatter];
    [formatter setDateFormat:@"HH"];
    NSString *status = [formatter stringFromDate:self];
    if (status.intValue > 0 && status.intValue < 12) {
        return @"上午好";
    }else{
        return @"下午好";
    }
    return @"";
}

#pragma mark - 根据项目添加的功能
+(NSString *)timeIntervalSinceNow:(NSString *)theDate withDataFormat:(NSString *)DateFormat{
    NSDateFormatter *dateFormatter = [NSDate formatter];
    //如果给定的时间格式中包括a(AM PM) 那么就要设置locale属性进行设置,使得它强制采用“en-US”的方式
    //否则如果设置中的语言设置是中文 那么a格式就会代表 (上午  下午)
    [dateFormatter setDateFormat:DateFormat];
    dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    
    //测试时出现3小时误差 原因是模拟器的设置时区不是北京时间，而给的时间是北京时间。两个时间的时区不同。
    //所以解决办法是将NSDateFormatter设置时区为东八区 "GMT+0800" 并将系统当前时间也强制转成东八区
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0800"]];
    //[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    
    NSDate *giveDate = [dateFormatter dateFromString:theDate];
    NSTimeInterval late = [giveDate timeIntervalSince1970]*1;
    //NSLog(@"giveData = %@",[dateFormatter stringFromDate:giveDate]);
    //NSDate *nowDate1 = [NSDate dateWithTimeIntervalSinceNow:0];
    //iOS中的时区表示方法：GMT+0800 GMT-0800。(+：东区 -：西区 08：小时数 00：分钟数)。 GMT+0830就是指比GMT早8小时外加30分钟的时区。
    //NSLog(@"now:%@", [dateFormatter stringFromDate:[NSDate date]]);
    NSDate *nowDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate date]]];
    //NSDate *nowDate = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now = [nowDate timeIntervalSince1970]*1;
    NSString *timeString=@"";
    NSTimeInterval interval = now-late;
    //NSTimeInterval interval = [giveDate timeIntervalSinceDate:nowDate];
    //NSLog(@"interval = %f",interval);
    //给的时间在一个小时之内，显示分钟
    if (interval/3600 < 1) {
        if (interval/60 < 1) {
            timeString = @"1";
            return @"刚刚";
        }else{
            timeString = [NSString stringWithFormat:@"%f", interval/60];
            timeString = [timeString substringToIndex:timeString.length-7];
        }
        timeString = [NSString stringWithFormat:@"%@分钟前",timeString];
    }
    //给的时间在一小时以上24小时以内
    else if (interval/3600 > 1 && interval/86400 < 1){
        timeString = [NSString stringWithFormat:@"%f", interval/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@小时前", timeString];
    }
    //    发表在24以上10天以内
    else if (interval/86400>1&&interval/864000<1)
    {
        timeString = [NSString stringWithFormat:@"%f", interval/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        timeString=[NSString stringWithFormat:@"%@天前", timeString];
    }
    //    发表时间大于10天
    else
    {
        //1.取得后台给的时间的 年月日 (易出错地)
        NSArray *array = [theDate componentsSeparatedByString:@" "];
        timeString = [array objectAtIndex:0];
        //NSLog(@"timeString = %@",timeString);
        [dateFormatter setDateFormat:[[DateFormat componentsSeparatedByString:@" "] objectAtIndex:0]];
        NSDate *dayDate = [dateFormatter dateFromString:timeString];
        //NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        
        //2.与现在的年份比较，如果相等不显示年份
        [dateFormatter setDateFormat:@"yyyy"];
        NSString *dateStringYear = [dateFormatter stringFromDate:dayDate];
        NSString *nowDateYear = [dateFormatter stringFromDate:nowDate];
        if ([dateStringYear isEqualToString:nowDateYear]) {
            [dateFormatter setDateFormat:@"M月d日"];
            timeString = [dateFormatter stringFromDate:dayDate];
        }else{
            [dateFormatter setDateFormat:@"yy年M月d日"];
            timeString = [dateFormatter stringFromDate:dayDate];
        }
        
    }
    return timeString;
}

+ (NSString *)timeTransitionFromGiveDate:(NSString *)giveDateString andFormat:(NSString *)formatString toDateWithFormat:(NSString *)resultDateFormat{
    
    NSDateFormatter *dateFormatter = [NSDate formatter];
    dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setDateFormat:formatString];
    
    NSDate *giveDate = [dateFormatter dateFromString:giveDateString];
    
    [dateFormatter setDateFormat:resultDateFormat];
    NSString *resultDateString = [dateFormatter stringFromDate:giveDate];
    
    return resultDateString;
}

+ (NSTimeInterval)timeIntervalSinceNow:(NSString *)theDate withDateFormatString:(NSString *)formatString{
    
    NSDateFormatter *dateFormatter = [NSDate formatter];
    [dateFormatter setDateFormat:formatString];
    NSDate *calculateDate = [dateFormatter dateFromString:theDate];
    NSTimeInterval lateNum = [calculateDate timeIntervalSince1970]*1;
    
    NSDate *nowDate = [NSDate date];
    NSTimeInterval nowNum = [nowDate timeIntervalSince1970]*1;
    
    NSTimeInterval cha = lateNum - nowNum;
    return cha;
}

+ (NSDate *)timeGetDistanceNowDateWithNDay:(NSInteger)NDay{
    NSDate *nowDate = [NSDate date];
    NSTimeInterval oneDay = 24*60*60;//1天的秒数
    NSDate *theDate = [nowDate initWithTimeIntervalSinceNow:NDay * oneDay];
    return theDate;
}
+ (NSDate *)timeGetCustomDateWithHour:(NSInteger)hour minute:(NSInteger)minute{
    //获取当前时间
    NSDate *currentDate = [NSDate date];
    NSCalendar *currentCalendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *currentComps = [[NSDateComponents alloc]init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
    //根据参数设置当天的某个时间点
    NSDateComponents *resultComps = [[NSDateComponents alloc]init];
    [resultComps setYear:[currentComps year]];
    [resultComps setMonth:[currentComps month]];
    [resultComps setDay:[currentComps day]];
    [resultComps setHour:hour];
    [resultComps setMinute:minute];
    
    NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return [resultCalendar dateFromComponents:resultComps];
}

+ (BOOL)timeBetweenFromDate:(NSDate *)fromDate byAddingHourTimeInterval:(NSTimeInterval)hour {
    NSDate *todate = [fromDate dateByAddingTimeInterval:hour*60*60];
    return [self timeBetweenFromDate:fromDate toDate:todate];
}

+ (BOOL)timeBetweenFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate{
    NSDate *currentDate = [NSDate date];
    if ([currentDate compare:fromDate] == NSOrderedDescending && [currentDate compare:toDate] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}
- (BOOL)timeBetweenFromDate:(NSDate *)fromDate toDate:(NSDate *)toDate {
    if ([self compare:fromDate] == NSOrderedDescending && [self compare:toDate] == NSOrderedAscending) {
        return YES;
    }
    return NO;
}

+ (NSTimeInterval)timeDistanceSecondsBetweenDate:(NSDate *)fromDate toDate:(NSDate *)date {
    NSTimeInterval num1 = [fromDate timeIntervalSinceReferenceDate];
    NSTimeInterval num2 = [date timeIntervalSinceReferenceDate];
    return num1 - num2;
}

+ (NSDate *)timeGetDateWithTimeInterval:(NSTimeInterval)interval fromGiveDate:(NSDate *)giveDate {
    //时间原点
    NSTimeInterval giveNum = [giveDate timeIntervalSince1970];
    NSTimeInterval resultNum = giveNum + interval;
    return [NSDate dateWithTimeIntervalSince1970:resultNum];
}

+ (NSString *)timeGetStringFromDate:(NSDate *)date withFormat:(NSString *)format{
    NSDateFormatter *dateFormatter = [NSDate formatter];
    [dateFormatter setDateFormat:format];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}
+ (NSDate *)timeDateFromDateString:(NSString *)dateString withFormat:(NSString *)formatString{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    
    [dateFormatter setDateFormat:formatString];
    
    NSDate *giveDate = [dateFormatter dateFromString:dateString];
    return giveDate;
}

//把国际时间转换为当前系统时间
- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}

//获取周几
+ (NSString *)timeGetWeekStringFromDate:(NSDate *)date {
    NSInteger weekday = [date weekday];
    NSArray *weekArray = @[@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六"];
    if (weekday-1 < 7) {
        NSString *weekStr = weekArray[weekday-1];
        return weekStr;
    }
    return @"";
}
//获取距离当前时间的几天的日期数组
+ (NSArray <NSDate *> *)timeGetDays:(NSInteger)days withLatelyOrFuture:(BOOL)tag{
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:days];
    for (NSInteger i = 0; i < days; i++) {
        NSTimeInterval secondsPerDay = i * 24*60*60;
        secondsPerDay = tag?secondsPerDay:-secondsPerDay;
        NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
        [array addObject:curDate];
    }
    return array;
}

+ (NSArray <NSString *> *)timeGetDays:(NSInteger)days withLatelyOrFuture:(BOOL)tag dateFormat:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    NSArray <NSDate *> *dates = [self timeGetDays:days withLatelyOrFuture:tag];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:days];
    for (NSInteger i = 0; i < days; i++) {
        NSString *dateStr = [dateFormatter stringFromDate:dates[i]];
        [array addObject:dateStr];
    }
    return array;
}

+ (NSArray <NSString *> *)timeGetWeekdayWithDays:(NSInteger)days withLatelyOrFuture:(BOOL)tag {
    NSArray <NSDate *> *dates = [self timeGetDays:days withLatelyOrFuture:tag];
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:days];
    for (NSInteger i = 0; i < days; i++) {
        NSString *dateStr = [self timeGetWeekStringFromDate:dates[i]];
        [array addObject:dateStr];
    }
    return array;
}

@end
